<template>
  <el-config-provider :locale="zhCn">
    <RouterView />
  </el-config-provider>
</template>

<script setup>
import { onBeforeMount, onBeforeUnmount, onMounted } from 'vue'
import { RouterView } from 'vue-router'
import { ElConfigProvider } from 'element-plus'
import { getRoleByTeacherId } from '@/apis'

import zhCn from 'element-plus/es/locale/lang/zh-cn'
import 'element-plus/es/components/message/style/css'
import { useAuthStore, useTaskStore } from '@/stores'

const authStore = useAuthStore()
const taskStore = useTaskStore()
// 获取用户信息以及权限
const getPermission = async () => {
  const { userInfo, setNowGlobalRole, nowGlobalRole, setRoles } = authStore

  if (!userInfo.userId) return

  if (!userInfo.school_id) {
    await authStore.getUserInfoFun()
  }

  const hasValidIds = userInfo.userId && userInfo.school_id
  if (hasValidIds) {
    const res = await getRoleByTeacherId({
      teacherId: userInfo.userId,
      schoolId: userInfo.school_id
    })

    if (res.data) {
      setRoles(res.data)
    }

    if (!nowGlobalRole) {
      setNowGlobalRole({ role_name: '任课老师', role_code: '' })
    }
  }
}

onMounted(() => {
  taskStore.createBroadcastChannel()
})

onBeforeUnmount(() => {
  taskStore.destroyBroadcastChannel()
})

onBeforeMount(getPermission)
</script>
